#include "songitemwidget.h"
#include "ui_songitemwidget.h"
#include "songmanager.h"
#include <QDebug>

SongItemWidget::SongItemWidget(QWidget *parent) :
    QWidget(parent),
    _playing(false),
    _connected(false),
    _mouseInWidget(false),
    _mouseInButton(false),
    _animations(3, nullptr),
    _animationLabels(3, nullptr),
    ui(new Ui::SongItemWidget)
{
    ui->setupUi(this);

    ui->SongItemWidgetStyle->installEventFilter(this);
    ui->pushButton_index->installEventFilter(this);
    connect(ui->pushButton_index, &QPushButton::clicked, this, &SongItemWidget::play);
    createAnimation();
}

SongItemWidget::~SongItemWidget()
{
    delete ui;
}

bool SongItemWidget::eventFilter(QObject *watched, QEvent *event)
{
    if (watched == ui->SongItemWidgetStyle){
        if (event->type() == QEvent::Enter){ // qDebug() << "有事件--Enter SongItemWidgetStyle";
            _mouseInWidget = true;
            ui->pushButton_index->setText(""); //进入清空
            setIndexIcon(true);

            stopAnimation();
        } else if (event->type() == QEvent::Leave){ // qDebug() << "有事件--Leave SongItemWidgetStyle";
            _mouseInWidget = false;
            setIndexIcon(false);

            if(_playing) startAnimation();
            else ui->pushButton_index->setText(_index); //离开重置
        }
    } else if(watched == ui->pushButton_index){
        if (event->type() == QEvent::Enter){ // qDebug() << "有事件--Enter pushButton_index";
            _mouseInButton = true;
            setIndexIcon(true, true);
        } else if (event->type() == QEvent::Leave){ // qDebug() << "有事件--Leave pushButton_index";
            _mouseInButton = false;
            setIndexIcon(true);
        }
    }
    return QWidget::eventFilter(watched, event);
}

void SongItemWidget::mouseDoubleClickEvent(QMouseEvent *event)
{
    qDebug() << "DoubleClick SongItemWidget";
//    ui->pushButton_index->setChecked(!_playing);
    ui->pushButton_index->click();
    setIndexIcon(true);
    QWidget::mouseDoubleClickEvent(event);
}
//选中为true,取消选中为false
void SongItemWidget::play(bool play)
{
    qDebug() << _songItem.name << "的播放按键被点击, play = " << play;
    if(_songItem.url().isEmpty()){
        qDebug() << "没用的url";
        ui->pushButton_index->setChecked(false);
        return;
    }

    if(_connected == false){///////////////////////////
        connectManager();
    }

    _playing = play;
    int index = _index.toInt() - 1; // _index是从01开始的
    if(_playing) { qDebug() << "开始播放";
        emit played(index, true); // 这里的参数暂时只传数字,后面看情况添加
    } else { qDebug() << "暂停播放";
        emit played(index, false);
    }
}

void SongItemWidget::setArtist(const QString &artist)
{
    _songItem.artist = artist;
    ui->pushButton_artist->setText(_songItem.artist);
}

void SongItemWidget::setName(const QString &name)
{
    _songItem.name = name;
    ui->label_name->setText(_songItem.name);
}

void SongItemWidget::setImage(const QString &path)
{
    QPixmap pixmap(path);
    setImage(pixmap);
}


#include <QPainter>
void SongItemWidget::setImage(QPixmap pixmap)
{
    _songItem.image = pixmap;

    // 目标大小
    QSize targetSize = ui->label_image->size();
    qDebug() << "targetSize = " << targetSize;
    pixmap = _songItem.image.scaled(targetSize, Qt::KeepAspectRatio, Qt::SmoothTransformation);
    QPixmap roundedPixmap(pixmap.size());
    roundedPixmap.fill(Qt::transparent);

    QPainter painter(&roundedPixmap);
    painter.setRenderHint(QPainter::Antialiasing);
    painter.setPen(Qt::NoPen);
    painter.setBrush(QBrush(pixmap));
    painter.drawRoundedRect(pixmap.rect(), 10, 10);

//    ui->label_image->setPixmap(_songItem.image);
    ui->label_image->setPixmap(roundedPixmap);
}

void SongItemWidget::setAlbum(const QString &album)
{
    _songItem.album = album;
    ui->pushButton_album->setText(_songItem.album);
}

void SongItemWidget::setIsLike(bool isLike)
{
    _songItem.isLike = isLike;
    ui->radioButton_like->setChecked(_songItem.isLike);
}
//设置歌曲索引（序号）
void SongItemWidget::setIndex(int index)
{
    qDebug() << "SongItemWidget::setIndex : " << index;
    _index = QString::number(index);
    while(_index.size() < 2) _index.push_front('0');
    ui->pushButton_index->setText(_index);
}

void SongItemWidget::setDuration(int ms) //设置歌曲时长， 转化为秒为单位
{
    _songItem.duration = ms;
    QString min = QString::number(_songItem.duration / 1000 / 60);
    while(min.size() < 2) min.push_front("0");
    QString sec = QString::number(_songItem.duration / 1000 % 60);
    while(sec.size() < 2) sec.push_front("0");
    QString duration = min + ":" + sec;
    ui->label_duration->setText(duration);
}

void SongItemWidget::setUrl(QUrl url)
{
    if(url.isLocalFile()){
        _songItem.local_url = url;
    } else {
        _songItem.wangyiyun_url = url;
    }
}
//设置歌曲项中图片大小
void SongItemWidget::setImageSize(int px)
{
    ui->label_image->setMaximumWidth(px);
    ui->label_image->setMaximumHeight(px);
    ui->label_image->setMinimumWidth(px);
    ui->label_image->setMinimumHeight(px);
    //返回当前this控件的几何属性，包括位置和大小
    QRect rect = this->geometry();
    rect.setX(ui->label_image->x());
    rect.setY(2);
    rect.setSize(QSize(px, px));
    ui->label_image->setGeometry(rect);
    qDebug() << rect;
}
//将当前 SongItemWidget 关联到全局的 SongManager，建立信号槽连接，实现歌曲播放、喜欢、下载等状态的自动同步和响应。
void SongItemWidget::connectManager()
{
    qDebug() << _songItem.name << "开始连接";
    if (_songItem.url().isEmpty()){
       qDebug() << "没用的url, 不用connectManager";
       return;
    }
    if (_connected == false){
        connect(SongManager::instance() ,&SongManager::played, this, &SongItemWidget::on_songManager_played);
        connect(SongManager::instance(), &SongManager::liked,  this, &SongItemWidget::on_songManager_liked);
        connect(SongManager::instance(), &SongManager::downloaded, this, &SongItemWidget::on_songManager_downloaded);
        _connected = true;
    }
    SongManager::instance()->addSongItem(_songItem);
    on_songManager_played(_songItem.url(), _songItem.isPlaying);
    setIsLike(_songItem.isLike);
    qDebug() << _songItem.name << " 已连接";
}
//初始化歌曲项SongItem
void SongItemWidget::setSongItem(const SongItem &songItem)
{
    qDebug() << "设置歌曲信息";
    qDebug() << songItem.name << '-' << songItem.artist << '-' << songItem.album;
    qDebug() << "----------";
    setUrl(songItem.url());
    setName(songItem.name);
    setAlbum(songItem.album);
    setArtist(songItem.artist);
    setDuration(songItem.duration);
    setImage(songItem.image);
    setIsLike(songItem.isLike);
}

void SongItemWidget::setIndexIcon(bool haveIcon, bool hover)
{
    if (haveIcon){
        if (hover){
            if (_playing) ui->pushButton_index->setIcon(QIcon(":/image/ui/songitem/pause_100.png"));
            else ui->pushButton_index->setIcon(QIcon(":/image/ui/songitem/play_100.png"));
        } else {
            if (_playing) ui->pushButton_index->setIcon(QIcon(":/image/ui/songitem/pause_50.png"));
            else ui->pushButton_index->setIcon(QIcon(":/image/ui/songitem/play_50.png"));
        }
    } else {
        ui->pushButton_index->setIcon(QIcon(""));
    }
}

void SongItemWidget::createAnimation()
{
    int a_h = -4; // 微调高度
    // 坐标,把图画出来就清楚了
    QLabel* l1 = new QLabel(this);
    QPropertyAnimation* a1 = new QPropertyAnimation(l1, "geometry");
    a1->setKeyValueAt(0.00, QRect(30,a_h+ 32,     4,-a_h+ 20));
    a1->setKeyValueAt(0.10, QRect(30,a_h+ 32,     4,-a_h+ 20));
    a1->setKeyValueAt(0.30, QRect(30,a_h+ 32 + 8, 4,-a_h+ 20 - 8));
    a1->setKeyValueAt(0.50, QRect(30,a_h+ 32 +16, 4,-a_h+ 20 -16));
    a1->setKeyValueAt(0.70, QRect(30,a_h+ 32 + 8, 4,-a_h+ 20 - 8));
    a1->setKeyValueAt(0.90, QRect(30,a_h+ 32,     4,-a_h+ 20));
    a1->setKeyValueAt(1.00, QRect(30,a_h+ 32,     4,-a_h+ 20));
    a1->setLoopCount(-1);
    a1->setDuration(1000);

    QLabel* l2 = new QLabel(this);
    QPropertyAnimation* a2 = new QPropertyAnimation(l2, "geometry");
    a2->setKeyValueAt(0.00, QRect(38,a_h+ 40,     4,-a_h+ 12));
    a2->setKeyValueAt(0.10, QRect(38,a_h+ 40,     4,-a_h+ 12));
    a2->setKeyValueAt(0.30, QRect(38,a_h+ 40 + 8, 4,-a_h+ 12 - 8));
    a2->setKeyValueAt(0.50, QRect(38,a_h+ 40,     4,-a_h+ 12));
    a2->setKeyValueAt(0.70, QRect(38,a_h+ 40 - 8, 4,-a_h+ 12 + 8));
    a2->setKeyValueAt(0.90, QRect(38,a_h+ 40,     4,-a_h+ 12));
    a2->setKeyValueAt(1.00, QRect(38,a_h+ 40,     4,-a_h+ 12));
    a2->setLoopCount(-1);
    a2->setDuration(1000);

    QLabel* l3 = new QLabel(this);
    QPropertyAnimation* a3 = new QPropertyAnimation(l3, "geometry");
    a3->setKeyValueAt(0.00, QRect(46,a_h+ 48,     4,-a_h+ 4));
    a3->setKeyValueAt(0.10, QRect(46,a_h+ 48,     4,-a_h+ 4));
    a3->setKeyValueAt(0.30, QRect(46,a_h+ 48 - 8, 4,-a_h+ 4 + 8));
    a3->setKeyValueAt(0.50, QRect(46,a_h+ 48 -16, 4,-a_h+ 4 +16));
    a3->setKeyValueAt(0.70, QRect(46,a_h+ 48 - 8, 4,-a_h+ 4 + 8));
    a3->setKeyValueAt(0.90, QRect(46,a_h+ 48,     4,-a_h+ 4));
    a3->setKeyValueAt(1.00, QRect(46,a_h+ 48,     4,-a_h+ 4));
    a3->setLoopCount(-1);
    a3->setDuration(1000);

    QString style("background-color:rgba(255, 58, 58, 200);");
    l1->setStyleSheet(style);
    l2->setStyleSheet(style);
    l3->setStyleSheet(style);

    _animations[0] = a1;
    _animations[1] = a2;
    _animations[2] = a3;
    _animationLabels[0] = l1;
    _animationLabels[1] = l2;
    _animationLabels[2] = l3;

    if (_playing)
        startAnimation();
    stopAnimation();
}

// #7E8491, hover:#394153

void SongItemWidget::on_pushButton_index_clicked()
{
    qDebug() << "on_pushButton_index_clicked";
    setIndexIcon(true, true);
}

void SongItemWidget::on_songManager_played(QUrl url, bool isPlay)
{
    if(_songItem.url() == url){
        qDebug() << url << " isPlay = " << isPlay;
        _playing = isPlay;
        if(isPlay){
            ui->pushButton_index->setChecked(true);
            if (!_mouseInButton && !_mouseInWidget)
                startAnimation(), ui->pushButton_index->setText("");
        } else {
            ui->pushButton_index->setChecked(false);
            stopAnimation();
            if (!_mouseInButton && !_mouseInWidget)
                ui->pushButton_index->setText(_index);
        }
        setIndexIcon(_mouseInWidget, _mouseInButton);
    }
}

void SongItemWidget::on_songManager_liked(QUrl url, bool isLike)
{
    if (url == _songItem.url()){
       _songItem.isLike = isLike;
       ui->radioButton_like->setChecked(isLike);
    }
}

void SongItemWidget::on_songManager_downloaded(QUrl url, const QString &path)
{
    if (url == _songItem.url()){
        _songItem.local_url = path;
        emit downloaded();
    }
}
//按钮从未选中变为选中:true
void SongItemWidget::on_radioButton_like_toggled(bool checked)
{
    _songItem.isLike = checked;
}

void SongItemWidget::startAnimation()
{
    for(auto e : _animations) e->start();
    for(auto e : _animationLabels) e->show();
}

void SongItemWidget::stopAnimation()
{
    for(auto e : _animations) e->stop();
    for(auto e : _animationLabels) e->hide();
}

void SongItemWidget::on_radioButton_like_clicked(bool checked)
{
    qDebug() << _songItem.name << "的喜欢按键被点击, checked = " << checked;
    if(_songItem.url().isEmpty()){
        qDebug() << "没用的url";
        ui->radioButton_like->setChecked(false);
        return;
    }
    if(_connected == false){
        connectManager();
    }
    _songItem.isLike = checked;
    if (_connected){
        SongManager::instance()->like(_songItem.url(), checked);
    }
}
